<?php

namespace app\api\controller\basics;

use think\Config;
use think\Db;

/**
 * 基础设置
 */
class Basics
{

	/**
	 * 实例对象
	 * @var object
	 */
	protected static $instance;


	protected $limit_nums = 10000;

	/**
	 * 默认配置
	 * @var array
	 */
	protected $config = [
		"prefix" 		=> "fd_",
		"user" 			=> "user",
		"borrow"		=> "balance_borrow",
		"balance"		=> "balance",
		"level"			=> "template_buy_level",
		"buy"			=> "equip_buy"
	];

	/**
	 * 默认架构方法
	 */
	public function __construct()
	{
	}

	/**
	 * 实例化
	 */
	public static function instance()
	{
		if (is_null(self::$instance)) {
			self::$instance = new static();
		}
		return self::$instance;
	}

	/**
	 * 锁 - 提现
	 */
	public function buy_order_status_update($id = 0)
	{
		if (!empty($id)) {
			$where = ["id" => $id];
			$check = Db::name($this->config["buy"])
				->where($where)
				->count();
			if ($check) {
				$ret = Db::name($this->config["buy"])
					->where($where)->update(["pay_status" => 1, "pay_time" => time()]);
				if ($ret) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 锁 - 提现
	 */
	public function user_level_update($uid = 0, $lev = "")
	{
		if (!empty($uid) && !empty($lev)) {
			$where = ["id" => $uid];
			$check = Db::name($this->config["user"])
				->where($where)
				->count();
			if ($check) {
				$ret = Db::name($this->config["user"])
					->where($where)->update(["buy_level" => $lev, "first_time" => 2]);
				if ($ret) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 获取PID
	 */
	public function pid($uid)
	{
		return Db::name($this->config["user"])
			->where("id = " . $uid)
			->value("pid");
	}

	/**
	 * 认购 上限 数
	 */
	public function buy_limit_nums($uid = 0)
	{
		$limit = $this->limit_nums;
		$pid = $this->pid($uid);
		if ($pid > 0) {
			$where = "agid = {$pid} and pay_status = 1 and status = 1";
			$check = Db::name($this->config["buy"])
				->where($where)
				->count();
			if ($check) {
				$limit = Db::name($this->config["buy"])
					->where($where)
					->order("create_time DESC")
					->value("nums");
			}
		}
		return $limit;
	}

	/**
	 * 认购等级
	 */
	public function get_buy_levels($nums)
	{
		$lev = "AG";
		if ($nums > 0) {
			$req = Db::name($this->config["level"])
				->where("state = 1")
				->field("start,end,code")
				->select();
			if ($req) {
				$arr = [];
				foreach ($req as $v) {
					$arr[$v["code"]] = $v["end"];
				}
				$max = max($arr);
				if ($max < $nums) {
					$lev = array_flip($arr)[$max];
				} else {
					foreach ($req as $vals) {
						if ($vals["start"] <= $nums && $vals["end"] >=  $nums) {
							$lev =  $vals["code"];
						}
					}
				}
			}
		}
		return $lev;
	}

	/**
	 * 用户名
	 */
	public function get_user_name($uid)
	{
		return Db::name($this->config["user"])->where("id= " . $uid)->value("mobile");
	}

	/**
	 * 用户昵称
	 */
	public function get_user_nickname($uid)
	{
		return Db::name($this->config["user"])->where("id= " . $uid)->value("nickname");
	}

	/**
	 * 代理 - 余额
	 */
	public function get_balance($uid)
	{
		$balance = 0;
		if ($uid) {
			$where = "";
			$where = "main_id = " . $uid;
			$check = Db::name("balance")
				->where($where)
				->count();
			if ($check) {
				$balance = Db::name("balance")->where($where)->value("money");
			}
		}
		return $balance;
	}

	/**
	 * 更新余额 - 减
	 * 
	 */
	public function sub_balance($agid, $money)
	{
		if ($agid) {
			$check = Db::name($this->config["balance"])
				->where("main_id = " . $agid)
				->count();
			if ($check) {
				$update = [
					"money" => Db::raw("money" . " - " . $money),
				];
				$ret = Db::name($this->config["balance"])->where("main_id = " . $agid)->update($update);
				if ($ret) return true;
			}
		}
		return false;
	}

	/**
	 * 还款更新余额 - 加
	 */
	public function repay_add_balance($agid, $money)
	{
		if ($agid) {
			$check = Db::name($this->config["balance"])
				->where("main_id = " . $agid)
				->count();
			if ($check) {
				$update = [
					"money" => Db::raw("money" . " + " . $money),
				];
				$ret = Db::name($this->config["balance"])->where("main_id = " . $agid)->update($update);
				if ($ret) return true;
			}
		}
		return false;
	}

	/**
	 * 更新余额 - 加
	 */
	public function add_balance($agid, $money)
	{
		if ($agid) {
			$check = Db::name($this->config["balance"])
				->where("main_id = " . $agid)
				->count();
			if ($check) {
				$update = [
					"money" => Db::raw("money" . " + " . $money),
					"total" => Db::raw("total" . " + " . $money)
				];
				$ret = Db::name($this->config["balance"])->where("main_id = " . $agid)->update($update);
				if ($ret) return true;
			} else {
				$data = [
					"main_type" => 2,
					"main_id"	=> $agid,
					"money"		=> $money,
					"total"		=> $money
				];
				$ret = Db::name($this->config["balance"])->insert($data);
				if ($ret) return true;
			}
		}
		return false;
	}

	/**
	 * 借 - 还款解冻提现
	 */
	public function repay_unlock_cash_out($uid = 0)
	{
		if (!empty($uid)) {
			$check_repay_req = Db::name($this->config["borrow"])
				->where("bid = {$uid} and repay = '2'")
				->count();
			if (!$check_repay_req) {
				$where = ["id" => $uid, "withdraw_state" => 2];
				$check_user_req = Db::name($this->config["user"])
					->where($where)
					->count();
				if ($check_user_req) {
					Db::name($this->config["user"])
						->where($where)->update(["withdraw_state" => 1]);
				}
			}
		}
	}

	/**
	 * 锁 - 提现
	 */
	public function lock_withdraw($uid = 0)
	{
		if (!empty($uid)) {
			$where = ["id" => $uid, "withdraw_state" => 1];
			$check = Db::name($this->config["user"])
				->where($where)
				->count();
			if ($check) {
				Db::name($this->config["user"])
					->where($where)->update(["withdraw_state" => 2]);
			}
		}
	}

	/**
	 * 借K记录
	 */
	public function get_borrow_info($id = 0)
	{
		$return = [];
		if (!empty($id)) {
			$return = Db::name($this->config["borrow"])
				->where("id = " . $id)
				->field("id,bid,loan_id,money,typs,repay")
				->find();
		}
		return $return;
	}

	/**
	 * 查看 有借款未还记录
	 */
	public function check_borrow_not_return($bid = 0)
	{
		if (!empty($bid)) {
			$check = Db::name($this->config["borrow"])
				->where("bid = {$bid} and state = 1 and typs = 'J' and repay = 2")
				->count();
			if ($check) return true;
		}
		return false;
	}

	/**
	 * 查看 查看 是否有赠送记JJ
	 */
	public function check_present($bid = 0)
	{
		if (!empty($bid)) {
			$check = Db::name($this->config["borrow"])
				->where("bid = {$bid} and state = 1 and typs = 'Z'")
				->count();
			if ($check) return true;
		}
		return false;
	}



	/**
	 * 查看 是否有赠送记录
	 */
	public function check_borrow_present_log($pid = 0, $cid = 0, $typ = "")
	{
		if (!empty($pid) && !empty($cid) && !empty($typ)) {
			$check = Db::name($this->config["borrow"])
				->where("bid = {$cid} and loan_id = {$pid}  and typs = '{$typ}' and state = 1")
				->count();
			if ($check) return true;
		}
		return false;
	}



	/**
	 * 查看 是否有借K记录
	 */
	public function check_borrow($bid = 0)
	{
		if (!empty($bid)) {
			$check = Db::name($this->config["borrow"])
				->where("bid = {$bid} and state = 1 and typs = 'J'")
				->count();
			if ($check) return true;
		}
		return false;
	}

	/**
	 * 查看 是否有借K记JJ
	 */
	public function check_borrow_log($pid = 0, $cid = 0)
	{
		if (!empty($pid) && !empty($cid)) {
			$check = Db::name($this->config["borrow"])
				->where("bid = {$cid} and loan_id = {$pid} and state = 1 and typs = 'J'")
				->count();
			if ($check) return true;
		}
		return false;
	}

	/**
	 * 验证 是否直属下级
	 */
	public function check_under($uid = 0, $cid = 0)
	{
		if (!empty($uid) && !empty($cid)) {
			$check = Db::name($this->config["user"])
				->where("(id = {$cid} or  id = {$uid})  and (pid = {$uid} or pid = {$cid})")
				->count();
			if ($check) return true;
			// $check_under = Db::name($this->config["user"])
			// 	->where("id = {$cid} and pid = {$uid}")
			// 	->count();
			// if ($check_under) {
			// 	return true;
			// } else {
			// 	$check_super =  Db::name($this->config["user"])
			// 		->where("id = {$uid} and pid = {$cid}")
			// 		->count();
			// 	if ($check_super) {
			// 		return true;
			// 	}
			// }
		}
		return false;
	}

	/**
	 * 创建订单号
	 */
	public function createUniqueNo()
	{
		#yCode 可以按照自己的实际情况调整
		$yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'I', 'K', 'L', 'Q', 'W', 'R', 'Y', 'U');
		$order_sn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));

		return $order_sn;
	}

	/**
	 * 密码验证
	 */
	public function payPassIsContinuity($pass)
	{
		//是纯数字  则判断是否连续
		if (is_numeric($pass)) {
			if (strlen($pass) != 6) {
				return true;
			}
			static $num = 1;
			for ($i = 0; $i < strlen($pass); $i++) {
				if (substr($pass, $i, 1) + 1 == substr($pass, $i + 1, 1)) {
					$num++;
				}
			}

			if ($num == strlen($pass)) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	// +--------------------------------------
	// | 数组分页函数 核心函数 array_slice
	// | 用此函数之前要先将数据库里面的所有数据按一定的顺序查询出来存入数组中
	// | @param [$list 分页数据 , $pageSize  每页多少条数据, $currPage   当前第几页 ,$sort  排序规则；例：array('time'=>'desc') ,  $group 分组]
	// | @MethodAuthor: HaiQing
	// | @Date: 2022-07-04 16:51:35
	// +--------------------------------------
	public function array_page($list, $currPage, $pageSize = 10, $sort = null, $group = null)
	{
		global $pageSizepage; #定全局变量
		$page = (empty($currPage)) ? 1 : $currPage; #判断当前页面是否为空 如果为空就表示为第一页面
		$start = ($page - 1) * $pageSize; #计算每次分页的开始位置
		//排序
		if (!empty($sort)) {
			$GLOBALS['sort'] = &$sort; #申明超全局变量
			unset($sort);
			uasort($list, function ($a, $b) {
				global $sort;
				foreach ($sort as $key => $val) {
					if ($a[$key] == $b[$key]) continue;
					return (($val == 'desc') ? -1 : 1) * (($a[$key] < $b[$key]) ? -1 : 1);
				}
			});
		}
		$totals = count($list);
		//分组
		if (!empty($group)) {
			$tem = array();
			foreach ($list as $val) {
				$tem[$val[$group]][] = $val;
			}
			unset($list);
			$list = $tem;
		}
		$pageSizepage = ceil($totals / $pageSize); #计算总页面数
		$page_data = array();
		$page_data = array_slice($list, $start, $pageSize, $group ? true : false);
		unset($GLOBALS['sort']);
		return $page_data;
	}
}
